import socket
import re
import sys

DOCUMENTS_ROOT = "./html"

class WSGIServer:
    """定义一个WSGI服务器"""
    def __init__(self,port,documents_root):
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.port = port
        # 确认端口复用
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # 绑定端口
        self.server_socket.bind(('', self.port))
        # 监听套接字
        self.server_socket.listen(128)
        #开启非阻塞
        self.server_socket.setblocking(False)
        self.client_lines = list()
        self.documents_root = documents_root

    def run_forever(self):
        while True:
            try :
                new_socket, new_addr = self.server_socket.accept()
            except:
                pass
            else:
                new_socket.setblocking(False)
                self.client_lines.append(new_socket)
            for client_socket in self.client_lines:
                try:
                    request = client_socket.recv(4096).decode('utf-8')
                except:
                    pass
                else:
                    if request:
                        self.deal_with_request(request,client_socket)
                    else:
                        client_socket.close()
                        self.client_lines.remove(client_socket)

    def deal_with_request(self, request, client_socket):
        """为这个浏览器服务器"""
        if not request:
            return
        request_lines = request.splitlines()
        ret = re.match(r'[^/]+(/[^ ]*)',request_lines[0])
        if ret:
            print(ret.group(1))
            file_name = ret.group(1)
            if file_name == "/":
                file_name ="/index.html"
        try:
            f = open("./html"+file_name,"rb")
        except:
            response_body = "not flie 请输入正确的url"
            response_head = "HTTP/1.1 404 NOT FOUND\r\n"
            response_head += "Content-Type: text/html; charset=utf-8\r\n"
            response_head += "Content-Length: %d\r\n"%len(response_body)
            response_head = "\r\n"
            client_socket.send(response_head.encode("utf-8"))
            client_socket.send(response_body.encode("utf-8"))
        else:
            html_centent = f.read()
            f.close()
            response_body = html_centent
            response_head = "HTTP/1.1 200 OK\r\n"
            response_head += "Content-Length: %d\r\n" % (len(response_body))
            response_head += "\r\n"
            # 发送response head发送给浏览器
            client_socket.send(response_head.encode('utf-8')+response_body)
            # 发送response boby给浏览器
            #new_socket.send(html_centent)

def main():
    if len(sys.argv) == 2:
        port = sys.argv[1]
        if port.isdigit():
            port = int(port)
    else:
        return
    http_server = WSGIServer(port, DOCUMENTS_ROOT)
    http_server.run_forever()


if __name__ == "__main__":
    main()